<script setup lang="ts">
import { isFunction, isObject } from '@/utils'
import { getCurrentInstance, ref, computed, onMounted } from 'vue'
import type { ComponentCustomProperties } from 'vue'

const FIRST = 'FIRST'
const OTHER = 'OTHER'

const count = ref(0)

const instance = getCurrentInstance()
const $electronApi: ComponentCustomProperties['$electronApi'] =
  instance?.appContext.config.globalProperties.$electronApi
const $ipcApi: ComponentCustomProperties['$ipcApi'] =
  instance?.appContext.config.globalProperties.$ipcApi

console.log('instance', instance)

const showFirstWindow = computed(() => !!$ipcApi?.value.otherRenderApi)
const showOtherWindow = computed(() => !!$ipcApi?.value.mainRenderApi)

onMounted(() => {
  $ipcApi?.value.addIpcListener(OTHER, (value: unknown) => {
    alert('我收到了来自其它window的值:' + value)
  })

  $ipcApi?.value.addIpcListener(FIRST, (value: unknown) => {
    alert('我收到了来自第一个window的值:' + value)
  })
})

const createWindow = () => {
  if (isObject($electronApi?.value) && isFunction($electronApi.value.createWindow)) {
    $electronApi.value.createWindow('http://localhost:3000/')
  }
}

const increateCount = () => {
  count.value++
  // alert(count.value)
}

const noticeFirst = () => {
  $ipcApi?.value.mainRenderApi?.fireMessage(OTHER, count.value)
}

const noticeOther = () => {
  $ipcApi?.value.otherRenderApi?.fireMessage(FIRST, count.value)
}
</script>

<template>
  <main>
    <div>count: {{ count }}</div>
    <vxe-button @click="createWindow">点我新建一个window，内容为自己</vxe-button>
    <vxe-button @click="increateCount">count+1</vxe-button>
    <vxe-button v-if="showFirstWindow" @click="noticeOther"
      >我是第一个window，只有我才展示该按钮，点我通知其它window</vxe-button
    >
    <vxe-button v-if="showOtherWindow" @click="noticeFirst"
      >我是第其它window，只有我才展示该按钮，点我通知第一个window</vxe-button
    >
  </main>
</template>
